import { download } from "@/utils/download";
import COS from "cos-js-sdk-v5";
const cos = new COS({
	SecretId: "AKID3va3ITRCoESTHsGQN7d4ISPGuLYBh187",
	SecretKey: "ub5NSL6g3EEtPinfKrBID1j5PYZRK2Xt",
});
const Bucket = "study-1316370007"; /* 填写自己的 bucket，必须字段 */
const Region = "ap-guangzhou"; /* 存储桶所在地域，必须字段 */
const basic = { Bucket, Region };

// 获取下载列表
export const getDownloadList = async () => {
	return new Promise((resolve, reject) => {
		cos.getBucket(basic, (err, data) => {
			if (err) {
				reject(err);
			} else {
				const result = data.Contents.map(i => ({ label: i.Key, value: i.Key }));
				resolve(result);
			}
		});
	});
};

// 上传文件
export function uploadFile(
	file: string,
	name: string,
	callback: (val: string) => {}
) {
	return new Promise((resolve, reject) => {
		cos.uploadFile(
			{
				...basic,
				Key: name,
				Body: file,
				SliceSize: 1024 * 1024 * 5,
				onProgress: data => {
					callback((data.percent * 100).toFixed());
				},
			},
			(err, data) => {
				if (err) {
					reject(err);
				} else {
					resolve(data);
				}
			}
		);
	});
}

// 下载文件
export function downloadFile(fileName: string) {
	cos.getObjectUrl({ ...basic, Key: fileName }, (err, data) => {
		data && download(data.Url, fileName);
	});
}

// 删除
export function delectFile(Key: string) {
	return new Promise((resolve, reject) => {
		cos.deleteObject({ ...basic, Key }, function (err, data) {
			if (err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
}
